package nc.bs.oa.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdf.util.BIPUtil;
import com.yonyou.ucf.mdf.util.HttpClientUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.bs.itf.qjb.IQjbService;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.oa.msg.IMessageIntegrateOAService;
import nc.vo.pub.BusinessException;
import ncc.bs.utils.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("restriction")
public class yonyouHOPToYFKService extends HttpServlet implements IHttpServletAdaptor {
	private static final String logName = "oalog";
	private BaseDAO baseDAO;
	private IQjbService qjbService;

	private static final long serialVersionUID = -4808637295385591788L;

	@Override
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		InputLogger.info(logName,"begin-------->1、第三方系统开始调用NCC单点登录【nc.bs.oa.servlet.yonyouHOPService】 ");
		PrintWriter pw = resp.getWriter();
		String url = null;
		try {
			NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(),"pfxx".getBytes());
			String dataSource = GetParamConfigUtil.queryGroupSysParam(GloableConfigParam.NCC_DATASOURCE);
			InvocationInfoProxy.getInstance().setUserDataSource(dataSource);
			InputLogger.info(logName,"--------2、第三方请求NCC调用的方法【yonyouHOPService】数据库模拟登陆完成：数据源="+dataSource );
			resp.setContentType("application/xml;charset=utf-8");
			resp.setCharacterEncoding("UTF-8");
			String userCode = req.getParameter("code");
			String from = req.getParameter("from");// in 内网、on 外网
			if(userCode == null || "".equals(userCode)) {
				throw new Exception("请求参数中登录用户code不允许为空!");
			}
			String nccaddr =  GetParamConfigUtil.queryGroupSysParam(GloableConfigParam.NCC_IP);
			url = nccaddr+"/service/yonyouHOPToYFK";
			Map<String, Object> requestParam = this.getRequestParam(userCode, url);
			// 获取单点登录url
			InputLogger.info(logName,"--------3、三方OA系统回调请求地址【"+url+"】");
			String oa_IPAndProt = GetParamConfigUtil.queryGroupSysParam(GloableConfigParam.OAURL);
			String tokenUrl = this.getOATokenUrl(oa_IPAndProt);
			InputLogger.info(logName,"--------4、token获取地址:,【"+tokenUrl+"】,请求参数:【"+ requestParam +"】");
			String getToken = HttpReqThirdPartyUtils.sendGet(tokenUrl, null, requestParam, logName);
			if(getToken == null || "".equals(getToken)) {
				throw new Exception("NCC获取OA token响应结果为空,请OA开发人员处理!");
			}
	        String token = getToken.split("&")[0].replace("access_token=", "");
			InputLogger.info(logName,"--------5、获取三方token,响应信息【"+token+"】");
			requestParam.put("access_token", token);
	        String oaProfileURL = this.getOAProfileURL(oa_IPAndProt);
			InputLogger.info(logName,"--------6.登陆人信息获取地址:,【"+oaProfileURL+"】,请求参数:【"+ requestParam +"】");
			String proFileBody = HttpReqThirdPartyUtils.sendGet(oaProfileURL, null, requestParam, logName);
			InputLogger.info(logName,"--------7.获取三方登录人信息,响应信息:【"+proFileBody+"】");
			if(proFileBody == null || "".equals(proFileBody)) {
				throw new Exception("NCC获取OA登录人信息异常,接口响应信息:【"+proFileBody+"】,请联系OA开发人员处理!");
			}
	        JSONObject resjson = JSON.parseObject(proFileBody);
	        Object OA_UserCode = resjson.get("id");
	        Object NC_UserCode = this.getBaseDAO().executeQuery("select user_code from sm_user where user_code = '"+OA_UserCode+"'",new ColumnProcessor());
			if(NC_UserCode == null ) {
	        	throw new Exception("当前用户编码在用友HOP系统不存在,用户编码: "+OA_UserCode+"请先确定用友HOP系统中是否存在当前!");
			}
	        Object mobile = this.getBaseDAO().executeQuery("select mobile from bd_psndoc where code = '"+OA_UserCode+"'",new ColumnProcessor());
			if(mobile == null ) {
	        	throw new Exception("请先确定当前人员【"+OA_UserCode+"】在用友HOPG系统是否维护手机号！");
			}
			String yfkURL = GetParamConfigUtil.queryGroupSysParam("YFKIP");
			String yfkAppKey = GetParamConfigUtil.queryGroupSysParam("YFKAppKey");
			String yfkAppSecret = GetParamConfigUtil.queryGroupSysParam("YFKAppSecret");
			String yfkjcrz = GetParamConfigUtil.queryGroupSysParam("YFKJCRZ"); // 集成认证中心
			String yfkqycode = GetParamConfigUtil.queryGroupSysParam("YFKQYCODE"); //
			String accessToken = this.getQjbService().getAccessToken("YFK",yfkURL, yfkAppKey, yfkAppSecret);
			if(accessToken == null || "".equals(accessToken)) throw new BusinessException("获取token异常");
			String userId = this.getQjbService().getQJBUserIdByPhoneToUserId("YFK", yfkURL, mobile.toString(), accessToken);
			if(userId == null || "".equals(userId)) throw new BusinessException("HOPG中人员信息中维护的手机号：【"+mobile+"】，暂无获取到友费控对应的人员信息");
			String loginResponse = this.getQjbService().getThirdLoginCode("YFK",yfkURL, accessToken, yfkjcrz, userId);
			if(loginResponse == null || "".equals(loginResponse)) throw new BusinessException("获取友费控集成认证临时登录code异常！");
			JSONObject jsonResponse = JSON.parseObject(loginResponse);
			String loginURL = "";
			if("200".equals(jsonResponse.getString("code"))) {
				JSONObject data = jsonResponse.getJSONObject("data");
				String code = data.getString("code");// 临时code
				if("".equals(code) || code == null || !data.getBoolean("isBindYhtUser") ) { // 该联邦用户中心尚未在友户通注册，无法使用单点登录服务 需要进入到注册界面
					loginURL = BIPUtil.getloginURL("YFK", code, yfkjcrz,yfkqycode,"https://euc.yonyoucloud.com",yfkURL);
				}else{ // 正常进行单点登录,说明不是第一次登陆
					loginURL = this.getQjbService().getSignLoginURL(yfkqycode,"YFK","https://euc.yonyoucloud.com", yfkjcrz,yfkURL+"/login", code);
				}
			}else{
				throw new BusinessException(loginResponse);
			}
	       resp.sendRedirect(loginURL);
		}catch(Exception e) {
			InputLogger.error(logName, "--------单点登录异常,异常信息:  "+e.getMessage());
			JSONObject error = ResultMessage.error(e.getMessage(), e);
			pw.println(error);
			return;
		}
        InputLogger.info(logName,"end-------->第三方系统开始调用NCC单登陆结束【nc.bs.oa.servlet.yonyouHOPService】 ");
	}

	/**
	 * 获取token请求三方地址
	 * @param OA_IpAndPort 三方ip+端口
	 * @return 
	 * @throws BusinessException
	 */
	private String getOATokenUrl(String OA_IpAndPort)  throws BusinessException {
		return "http://"+OA_IpAndPort+"/cas-server/oauth2.0/accessToken";
	}
	
	/**
	 * 获取当前当前登录人的信息
	 * @param OA_IpAndPort
	 * @return
	 * @throws BusinessException
	 */
	private String getOAProfileURL(String OA_IpAndPort)  throws BusinessException {
		return "http://"+OA_IpAndPort+"/cas-server/oauth2.0/profile";
	}
	/**
	 * 获取请求oa参数
	 * @param userCode 单点登录用户
	 * @param url      NCC单点登录地址
	 * @return
	 * @throws BusinessException
	 */
	private Map<String,Object> getRequestParam(String userCode, String url) throws BusinessException {
		Map<String, Object> map = new HashMap<>();
		map.put("code", userCode);
		map.put("redirect_uri", url);
		map.put("client_id", "yonyouHOPToYFK");
		map.put("client_secret", "334630");
		return map;
	}
	
	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}
	/**
	 * 获取旗舰版服务器
	 * @return
	 */
	public IQjbService getQjbService() {
		if(null == this.qjbService) {
			this.qjbService = NCLocator.getInstance().lookup(IQjbService.class);
		}
		return this.qjbService;
	}

	public BaseDAO getBaseDAO() {
		if(null == baseDAO) {
			baseDAO = new BaseDAO(InvocationInfoProxy.getInstance().getUserDataSource());
		}
		return baseDAO;
	}

}
